package com.study.demo.aop.proxy.jdk;

import com.study.demo.aop.proxy.jdk.annotation.After;
import com.study.demo.aop.proxy.jdk.annotation.Before;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: elvin
 * @time: 2019-10-09 16:51
 * @desc:
 **/
public class StudyJDKProxy implements InvocationHandler {

    private Object target;

    /*@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object res = null;
        if ("studyChinese".equals(method.getName())) {
            System.out.println(args[0] + "语文成绩很棒!");
            //执行目标方法
            res = method.invoke(target, args);
            System.out.println("语文老师非常喜欢" + args[0] + ", 因为这次语文考的好; ");
        }
        else if("studyEnglish".equals(method.getName())) {
            System.out.println(args[0] + "英语成绩一般般");
            //执行目标方法
            res = method.invoke(target, args);
            System.out.println("英语希望" + args[0] + "同学能够更加努力一点; ");
        }

        return res;
    }*/

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //根据方法上的注解, 来决定执行些什么方法
        Object res = null;
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations) {
            if(annotation instanceof Before){
                StudyMethod.before((String)args[0]);
                res = method.invoke(target, args);
            }
            else if(annotation instanceof After){
                res = method.invoke(target, args);
                StudyMethod.after((String)args[0]);
            }
        }
        return res;
    }

    public Object createProxyObj() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }


    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
    }
}
